<template>
  <view class="pay-container">
    <!-- 支付金额 -->
    <view class="amount-section" v-show="!showPaymentForm">
      <text class="label">支付金额</text>
      <text class="amount">¥{{ formatAmount(orderInfo.totalAmount) }}</text>
    </view>

    <!-- 支付方式 -->
    <view class="payment-methods" v-show="!showPaymentForm">
      <view class="section-title">选择支付方式</view>
      <view class="method-list">
        <view 
          class="method-item"
          v-for="method in paymentMethods" 
          :key="method.type"
          :class="{ active: selectedMethod === method.type }"
          @click="selectedMethod = method.type"
        >
          <view class="method-info">
            <image :src="method.icon" class="method-icon"></image>
            <text class="method-name">{{ method.name }}</text>
          </view>
          <uni-icons 
            :type="selectedMethod === method.type ? 'checkbox-filled' : 'circle'"
            :color="selectedMethod === method.type ? '#ff5500' : '#ddd'"
            size="20"
          ></uni-icons>
        </view>
      </view>
    </view>

    <!-- 支付按钮 -->
    <view class="bottom-bar" v-show="!showPaymentForm">
      <view class="order-info">
        <text class="label">订单金额：</text>
        <text class="value">¥{{ formatAmount(orderInfo.totalAmount) }}</text>
      </view>
      <button class="pay-btn" @click="handlePay" :loading="loading">
        立即支付
      </button>
    </view>

    <!-- 支付表单容器 -->
    <view v-if="showPaymentForm" class="payment-form-container">
      <web-view :src="paymentUrl"></web-view>
    </view>
  </view>
</template>

<script>
import payment from '@/config/api/modules/payment'
import { formatAmount } from '@/utils/common'

export default {
  data() {
    return {
      orderInfo: {
        orderIds: [],
        totalAmount: 0
      },
      selectedMethod: 'alipay',
      loading: false,
      showPaymentForm: false,
      paymentUrl: '',
      paymentFormHtml: '',
      paymentMethods: [
        {
          type: 'alipay',
          name: '支付宝支付',
          icon: '/static/images/payment/alipay.png'
        },
        {
          type: 'wechat',
          name: '微信支付',
          icon: '/static/images/payment/wechat.png'
        }
      ]
    }
  },

  onLoad(options) {
    // 从缓存获取订单信息
    const paymentInfo = uni.getStorageSync('paymentInfo')
    console.log('获取到的支付信息：', paymentInfo)
    
    if (paymentInfo) {
      // 确保orderIds是数组
      this.orderInfo = {
        orderIds: Array.isArray(paymentInfo.orderIds) ? paymentInfo.orderIds : [],
        totalAmount: paymentInfo.totalAmount || 0
      }
      
      // 打印处理后的订单信息
      console.log('处理后的订单信息：', this.orderInfo)
      
      // 验证数据
      if (!this.orderInfo.orderIds.length) {
        uni.showToast({
          title: '订单数据异常',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        return
      }
      
      uni.removeStorageSync('paymentInfo')
    } else {
      uni.showToast({
        title: '未获取到订单信息',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },

  methods: {
    formatAmount,
    
    // 处理web-view消息
    handleMessage(event) {
      console.log('收到web-view消息：', event)
    },
    
    async handlePay() {
      if (this.loading) return
      if (!this.orderInfo.orderIds.length) {
        uni.showToast({
          title: '订单数据异常',
          icon: 'none'
        })
        return
      }
      
      try {
        this.loading = true
        
        // 创建支付订单
        const paymentDTO = {
          orderIds: this.orderInfo.orderIds,
          paymentType: this.selectedMethod
        }
        
        console.log('发起支付请求参数：', paymentDTO)
        
        const res = await payment.createPayment(paymentDTO)
        console.log('支付请求响应：', res)
        
        // 检查响应状态
        if (res.code !== 200 || !res.data) {
          throw new Error(res.message || '获取支付链接失败')
        }

        // #ifdef H5
        // H5环境：创建临时表单并提交
        const tempDiv = document.createElement('div')
        tempDiv.innerHTML = res.data
        document.body.appendChild(tempDiv)
        const form = tempDiv.querySelector('form')
        if (form) {
          form.submit()
        } else {
          throw new Error('支付表单不存在')
        }
        // #endif

        // #ifdef MP-WEIXIN
        // 微信小程序：调用支付API
        uni.requestPayment({
          provider: 'wxpay',
          orderInfo: res.data,
          success: (res) => {
            console.log('支付成功', res)
            uni.showToast({
              title: '支付成功',
              icon: 'success'
            })
            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/order/list/index'
              })
            }, 1500)
          },
          fail: (err) => {
            console.error('支付失败', err)
            uni.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        })
        // #endif

        // #ifdef MP-ALIPAY
        // 支付宝小程序：调用支付API
        uni.requestPayment({
          provider: 'alipay',
          orderInfo: res.data,
          success: (res) => {
            console.log('支付成功', res)
            uni.showToast({
              title: '支付成功',
              icon: 'success'
            })
            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/order/list/index'
              })
            }, 1500)
          },
          fail: (err) => {
            console.error('支付失败', err)
            uni.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        })
        // #endif
        
      } catch (error) {
        console.error('支付请求失败：', error)
        uni.showToast({
          title: error.message || '支付失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss">
.pay-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.amount-section {
  background-color: #fff;
  padding: 60rpx 30rpx;
  text-align: center;
  margin-bottom: 20rpx;
  
  .label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    display: block;
  }
  
  .amount {
    font-size: 64rpx;
    color: #333;
    font-weight: bold;
  }
}

.payment-methods {
  background-color: #fff;
  padding: 30rpx;
  
  .section-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .method-list {
    .method-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      &.active {
        .method-name {
          color: #ff5500;
        }
      }
      
      .method-info {
        display: flex;
        align-items: center;
        
        .method-icon {
          width: 48rpx;
          height: 48rpx;
          margin-right: 20rpx;
        }
        
        .method-name {
          font-size: 28rpx;
          color: #333;
        }
      }
    }
  }
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .order-info {
    flex: 1;
    
    .label {
      font-size: 28rpx;
      color: #333;
    }
    
    .value {
      font-size: 36rpx;
      color: #ff5500;
      font-weight: bold;
    }
  }
  
  .pay-btn {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #ff5500;
    color: #fff;
    font-size: 32rpx;
    border-radius: 40rpx;
    
    &[loading] {
      opacity: 0.8;
    }
  }
}

.payment-form-container {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  background: #fff;
  
  .payment-iframe {
    width: 100%;
    height: 100%;
    border: none;
  }
}
</style> 